#include <Keyboard.h>

unsigned char keyCode[16]={'1','2','3','A',
                           '4','5','6','B',
						   '7','8','9','C',
						   'E','0','F','D'};

void InitKeyboard()
{
	DDRD=0x00;
	PORTD=0xf0;
}

unsigned char ScanKeyboard()
{
	unsigned char keyValue=0;
	unsigned char i;

	for (i=0;i<4;i++)
	{
		DDRD|=(1<<i);
		//PORTD&=~(1<<i);
		//_delay_us(10);

		switch(PIND&0xf0)
		{
			case 0b11100000:
				keyValue=1+i*4;
				break;
			case 0b11010000:
				keyValue=2+i*4;
				break;
			case 0b10110000:
				keyValue=3+i*4;
				break;
			case 0b01110000:
				keyValue=4+i*4;
				break;
			default:
				break;
		}

		DDRD&=~(1<<i);
		//PORTD|=(1<<i);

		if (keyValue>0)
			return keyCode[keyValue-1];
	}
	
	return 0xff;
}
